<template>
    <div class="examination">
        <div>
            <el-row style="background-color:#fff; padding: 5px 10px;border-radius: 5px;">
                <el-row>
                    <el-col :span="24">
                        <div class="grid-content bg-success clearfix">
                            <div style="float:left; line-height: 38px;">
                                距离考试结束还有: <span style="color:#f00">{{ showExamTime }}</span>
                            </div>
                            <div style="float: right; padding: 3px 0">
                                <el-button :type="ispermiss == true ? 'primary' : 'danger'" @click="submitExam">
                                    <i class="el-icon-plus"></i>
                                    <span>提交</span>
                                </el-button>
                            </div>

                        </div>
                    </el-col>
                </el-row>
            </el-row>

        </div>
        <el-row :gutter="20">
            <el-col :span="8">
                <!-- 左侧栏提示 -->
                <div class="left">
                    <div class="title">答题卡</div>
                    <div class="box">
                        <el-button :type="isExam == false ? 'danger' : 'info'" plain>未作答</el-button>
                        <el-button :type="isExam == true ? 'success' : 'info'" plain>已作答{{ examNum }}次</el-button>
                    </div>
                    <div class="title">选择题</div>
                    <div class="box">
                        <ul>
                            <li v-for="(item, i) in singleArr2" :class="myAnswers[i].done == true ? 'active' : ''"
                                @click="addCurrent(item.index)">{{ item.index }}
                            </li>
                        </ul>
                    </div>
                    <div class="title">多选题</div>
                    <div class="box">
                        <ul>
                            <li v-for="(item, i) in multiArr2"
                                :class="myAnswers[i + (singleArr2.length)].done == true ? 'active' : ''"
                                @click="addCurrent(item.index)">{{ item.index }}</li>
                          
                        </ul>
                    </div>
                    <div class="title">判断题</div>
                    <div class="box">
                        <ul>
                            <li v-for="(item, i) in judgeArr2"
                                :class="myAnswers[i + (singleArr2.length) + (multiArr2.length)].done == true ? 'active' : ''"
                                @click="addCurrent(item.index)">{{ item.index }}</li>
                        </ul>
                    </div>
                </div>
            </el-col>
            <el-col :span="16">
                <!-- 右侧栏内容 -->
                <div class="right">
                    <div class="single-choice" v-if="allTopic.length != 0">
                        <div class="quest"> <span>{{ num }}</span>.{{ allTopic[num - 1].topic_content }}</div>
                        <ul class="opt" :data-answer="allTopic[num - 1].topic_answer">
                            <div v-if="allTopic[num - 1].topic_type == '多选题'">
                                <li v-for="(item, i) in allTopic[num - 1].topic_options"
                                    @click="addMyMulti(item.opt, num, i)"
                                    :class="{ 'active': myAnswers[num - 1].options[i]['q'].isShow }">
                                    {{ item.opt }}.{{ item.text }}
                                </li>
                            </div>
                            <div v-else>
                                <li v-for="(item, i) in allTopic[num - 1].topic_options"
                                    @click="addMySingle(item.opt, num, i)"
                                    :class="{ 'active': myAnswers[num - 1].options[i].isShow }">
                                    {{ item.opt }}.{{ item.text }}
                                </li>
                            </div>
                        </ul>

                        <div style="margin-top:30px">
                            <el-button :type="num <= 1 ? 'info' : 'warning'" @click="addBack">
                                <i class="el-icon-back"></i>
                                <span>{{ startTips.length == 0 ? '上一题' : startTips }}</span>
                            </el-button>
                            <el-button :type="num >= total ? 'info' : 'warning'" @click="addNext">
                                <i class="el-icon-right"></i>
                                <span>{{ endTips.length == 0 ? '下一题' : endTips }}</span>
                            </el-button>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>

    </div>
</template>

<script>
import { topicDetail, topicLibDetail, scoreDetail, scorePartake, scoreAdd } from '../../api/index';

// 格式化时间
const downTime = (seconds) => {
    // const interval = () => {
    seconds--;
    if (seconds <= 0) {
        return {
            h: '00',
            m: '00',
            s: '00'
        }
    }
    let h = Math.floor(seconds / 3600);
    let m = Math.floor((seconds % 3600) / 60);
    let s = Math.floor(seconds % 60);

    h = h < 10 ? '0' + h : h;
    m = m < 10 ? '0' + m : m;
    s = s < 10 ? '0' + s : s;

    return `${h}小时${m}分钟${s}秒`
    // }
    // return interval()
}

export default {
    name: 'examination',
    data() {
        return {
            // 显示时间
            showExamTime: '00分钟00秒',
            // 用户考试所花的时间
            duration: 0,
            // 是否在指定时间提交试卷
            ispermiss: true,
            // 用户考试用时
            times: 0,
            // 按钮提示
            startTips: '',
            endTips: '',
            // 记录第几题
            num: 1,
            // 记录是否作答
            isExam: false,
            // 参与了多少次
            examNum: 0,
            // 单选题数量
            topic_single_count: 0,
            // 多选题数量
            topic_multi_count: 0,
            // 判断题数量
            topic_judge_count: 0,
            // 总数量
            total: 0,
            // 记录单选题
            singleArr: [],
            singleArr2: [],
            // 记录多选题
            multiArr: [],
            multiArr2: [],
            // 记录判断题
            judgeArr: [],
            judgeArr2: [],
            // 显示题目
            allTopic: [],
            // 记录用户选择的答案
            myAnswers: [],
            // 表单信息
            form: {
                topic_type: '单选题', // 题目类型
                topic_lib_name: '',// 题库
                topic_content: '',// 题目内容
                topic_analysis: '',//题目解析
                topic_val: 10,//分值
                topic_answer: '',//正确答案
                options: [
                    {
                        opt: '',
                        text: '',
                        desc: ''
                    },
                    {
                        opt: '',
                        text: '',
                        desc: ''
                    }
                ]
            },
            // 提交的考试信息
            formExam: {
                user_name: '', //用户姓名（1）
                score_val: 0, //用户得分数(9)
                score_exam_time: 0, // 用户考试用了多久(10)
                exam_options: '', // 考试结果 (11)
                exam_time: 0,// 考试总时长 (4)
                exam_type: '', //考试类型（7）
                topic_lib_id: '', //题库ID(2)
                exam_id: '', //考试ID（8）
                exam_name: '',//考试名称 (3)
                exam_fullcredit: 0,//总分 (5)
                exam_passline: 0,//及格线 (6)
            }
        }
    },
    methods: {
        // 获取该题库的题目并按要求做限制
        async topicDetailFunc(topic_lib_id, topic_single_count, topic_multi_count, topic_judge_count) {
            await topicDetail({ topic_lib_id }).then(content => {
                // console.log('1.0', content)
                let { code, msg, result } = content;
                if (code == 200) {
                    if (result.length == 0) {
                        return;
                    }

                    // (2)题库ID
                    this.formExam.topic_lib_id = topic_lib_id;

                    result.forEach((item, i) => {
                        let obj = {}
                        obj['topic_content'] = item.topic_content;
                        obj['topic_answer'] = item.topic_answer;
                        obj['topic_options'] = item.topic_options;
                        obj['topic_type'] = item.topic_type;
                        obj['topic_val'] = item.topic_val;
                        // (1)用户名
                        // this.formExam.user_name =item.user_name;

                        // 去除转义 '\'
                        // console.log('xx--->',item.topic_options)
                        let options_str = item.topic_options && item.topic_options.replace(/\\/g, "");
                        options_str = options_str.slice(1, options_str.length - 1);
                        // console.log("options_str:",options_str)
                        obj['topic_options'] = JSON.parse(options_str);

                        // 进行分类
                        let topic_type = item.topic_type;

                        // 获取题库数量的题目
                        if (topic_type == '单选题' && this.singleArr.length <= topic_single_count) {
                            this.singleArr.push(obj);
                        }

                        if (topic_type == '多选题' && this.multiArr.length <= topic_multi_count) {

                            this.multiArr.push(obj);
                        }

                        if (topic_type == '判断题' && this.judgeArr.length <= topic_judge_count) {
                            this.judgeArr.push(obj);
                        }

                        return obj;
                    })


                    // console.log('x:', arr);
                    // let newArr = [... this.singleArr, ...this.multiArr,... this.judgeArr];
                    // console.log(newArr);
                    this.allTopic = [... this.singleArr, ...this.multiArr, ... this.judgeArr];
                    // console.log('题目信息:', this.allTopic);
                    this.total = this.allTopic.length;
                    // 整合数据
                    let index = 0;
                    this.singleArr2 = this.singleArr.map((item, row) => {
                        this.myAnswers[index] = {
                            done: false,
                            topic_type: item.topic_type,
                            options: item.topic_options.map((ele, col) => {
                                return { point: `${index}${col}`, isShow: false }
                            })
                        };
                        index++
                        item.index = index;

                        return item;
                    })

                    // 处理多选题的选择
                    this.multiArr2 = this.multiArr.map((item, row) => {
                        this.myAnswers[index] = {
                            done: false,
                            topic_type: item.topic_type,
                            arr: [],
                            options: item.topic_options.map((ele, col) => {
                                let q = { isShow: false, a: '' }
                                return { point: `${index}${col}`, isShow: false, q }
                            })
                        };
                        index++
                        item.index = index;
                        return item;
                    })

                    console.log("2:", this.myAnswers)
                    this.judgeArr2 = this.judgeArr.map((item, row) => {
                        // done: false, 判断是否已经作答了
                        this.myAnswers[index] = {
                            done: false,
                            topic_type: item.topic_type,
                            options: item.topic_options.map((ele, col) => {
                                return { point: `${index}${col}`, isShow: false }
                            })
                        };
                        index++
                        item.index = index;
                        return item;
                    })
                    // console.log( this.myAnswers )
                    // 默认第一题开始
                    // this.myAnswers[0].done = true;
                }
            })
        },
        // 获取题库信息
        async topicLibDetailFunc(topic_lib_id) {
            await topicLibDetail({ topic_lib_id }).then(res => {
                // console.log('2.0', res)
                if (res.code == 200) {
                    // 单选题数量
                    // this.topic_single_count= res.result[0].topic_single_count;
                    // 多选题数量
                    // this.topic_multi_count= res.result[0].topic_multi_count;
                    // 判断题数量
                    // this.topic_judge_count= res.result[0].topic_judge_count;
                    // 整合数据
                    let { topic_single_count, topic_multi_count, topic_judge_count, topic_lib_name, exam_time, exam_fullcredit, exam_passline, exam_type } = res.result[0];
                    // (3)考试名称
                    this.formExam.exam_name = topic_lib_name;
                    // (4)考试总时长
                    this.formExam.exam_time = exam_time;
                    // (5)总分
                    this.formExam.exam_fullcredit = exam_fullcredit;
                    // (6)及格线
                    this.formExam.exam_passline = exam_passline;
                    // (7)考试类型
                    this.formExam.exam_type = exam_type;


                    this.times = exam_time * 60;
                    // 格式时间
                    this.examTimeFunc(this.times);
                    return { topic_lib_id, topic_single_count, topic_multi_count, topic_judge_count, topic_lib_name };
                }
            })
                .then(
                    data => {
                        // console.log("data:",data);
                        let { topic_lib_id, topic_single_count, topic_multi_count, topic_judge_count } = data;
                        // 获取题目
                        this.topicDetailFunc(topic_lib_id, topic_single_count, topic_multi_count, topic_judge_count);
                    }
                )
        },

        // 获取成绩信息
        async scoreDetailFunc(topic_lib_id) {
            await scoreDetail({ topic_lib_id }).then(content => {
                // console.log('3.0', content)
                if (content.code == 200) {
                    // 长度不为0 说明用户已经参与考试了
                    if (content.result.length != 0) {
                        this.isExam = true;
                        this.examNum = content.result.length;
                    }
                }
            })
        },

        // 点击上一题
        addBack() {
            // this.num = this.num <= 1 ? 1 : --this.num;
            this.num--;
            if (this.num <= 1) {
                this.num = 1;
                // this.startTips = "第一题"
                return;
            }
        },

        // 点击下一题
        addNext() {
            // this.num = this.num >= this.total ? this.total : ++this.num;
            this.num++;
            if (this.num >= this.total) {
                this.num = this.total;
                // this.endTips = "最后一题"
                return;
            }
        },

        // 选择指定的题目
        addCurrent(num) {
            this.num = num;
            if (this.num >= this.total) {
                this.num = this.total;
                // this.endTips = "最后一题"
                return;
            }

            if (this.num <= 1) {
                this.num = 1;
                // this.startTips = "第一题"
                return;
            }
        },

        // 处理单选和判断题
        addMySingle(opt, num, col) {
            let p = (num - 1) + "" + col;
            // console.log('坐标:', p)
            this.myAnswers[num - 1].answer = opt;
            this.myAnswers[num - 1].done = true;
            let x = 0;
            let arr = this.myAnswers.map((items, i) => {
                let arr2 = items.options.map((col, j) => {
                    if (p == col.point) {
                        col.isShow = true;
                        x = j;
                    }
                    // else {
                    //     col.isShow = false;
                    // }
                    return col
                })
                items.options = arr2;
                return items;
            })

            // 重新选择
            arr[num - 1].options.forEach(
                (optItem, x0) => {
                    if (x == x0) {
                        optItem.isShow = true;
                        // console.log("optItem1,",optItem);
                    }
                    else {
                        optItem.isShow = false;
                        // console.log("optItem2,",optItem);
                    }
                }
            )
            // 重新复制（响应式）
            this.myAnswers = arr;
            console.log('第（' + num + '）题:', '单选或判断题答案：', this.allTopic[num - 1].topic_content, opt);
        },

        // 处理多选题
        addMyMulti(opt, num, col) {
            let p = (num - 1) + "" + col;
            // console.log('坐标:', p)
            let arr = this.myAnswers.map((items, i) => {
                let arr2 = items.options.map((col, j) => {
                    if (p == col.point) {
                        // col.isShow = true;
                        if (col.q['isShow']) {
                            col.q['a'] = '';
                            col.q['isShow'] = false;
                        } else {
                            col.q['a'] = opt;
                            col.q['isShow'] = true;
                        }
                    }
                    return col
                })
                items.options = arr2;
                return items;
            })
            this.myAnswers[num - 1].done = true;
            this.myAnswers = arr;
            // console.log('3:',arr);
            this.myAnswers[num - 1].answer = "";
            this.myAnswers.forEach((item, i) => {
                item.options.forEach(ele => {
                    // console.log(i,ele);
                    if (ele.q) {
                        if (ele.q['a'].length == 1) {
                            item.answer += ele.q['a'];
                        }
                    }
                })
            })
            // num 从1开始  数组是从0开始
            console.log('第（' + num + '）题:', '多选题答案：', this.allTopic[num - 1].topic_content, this.myAnswers[num - 1].answer);
        },

        // 处理考试时间
        examTimeFunc(s) {
            let t = setInterval(() => {
                s--;
                if (s <= 0) {
                    this.ispermiss = false;
                    this.$message({
                        message: '考试时间结束',
                        type: 'warning'
                    });
                    clearInterval(t);
                    return;
                }
                this.showExamTime = downTime(s);
                this.duration++;
            }, 1000);
            // console.log(obj);
            this.showExamTime = downTime(s);
            this.duration++;
        },

        // 提交试卷
        submitExam() {
            // 在指定考试时间内容提交试卷
            if (this.ispermiss) {
                // console.log( this.allTopic, this.myAnswers)
                if (confirm('是否确定提交试卷吗?')) {
                    // 批改试卷
                    this.testPaper(this.allTopic, this.myAnswers);
                }
            }
            else {
                this$.message({
                    message: '您已经超过了答题时间',
                    type: 'warning'
                })
            }
        },

        // 审阅试卷
        async testPaper(examArr, answerArr) {
            // console.log({ examArr, answerArr });
            // user_name, score_val, score_exam_time, exam_options, exam_time, exam_type, topic_lib_id, exam_id, exam_name, exam_fullcredit, exam_passline
            let total_val = 0;
            // 记录用户答题结果
            let arr = [];
            for (let i = 0; i < examArr.length; i++) {
                // 空对象
                let obj = {};
                obj.topic_answer = examArr[i].topic_answer;
                obj.topic_content = examArr[i].topic_content;
                let arr2 = [];
                let options = examArr[i].topic_options;
                for (let j = 0; j < options.length; j++) {
                    let o = {};
                    o.opt = options[j].opt;
                    o.cdesc = options[j].desc;
                    o.text = options[j].text;
                    arr2.push(o);
                }
                obj.topic_options = arr2;
                // obj.topic_options = JSON.stringify(arr2);
                obj.topic_type = examArr[i].topic_type;
                obj.topic_val = examArr[i].topic_val;
                obj.answer = answerArr[i].answer;
                // 匹配答案
                if (examArr[i].topic_answer == answerArr[i].answer) {
                    total_val += (examArr[i].topic_val) - 0;
                }
                arr.push(obj);
                // console.log(i, "---->", answerArr[i].answer);
            }
            // console.log("得分:", total_val);
            // console.log("用户考试用时:", this.duration);
            // console.log("考试结果:", arr);
            // console.log("考试结果:", JSON.stringify(arr));
            // （1）获取用户姓名
            this.formExam.user_name = localStorage.getItem('user_name') || '未知';// 如果没有用户姓名，请重新登录
            // (9) 用户得分
            this.formExam.score_val = total_val;
            //  (10) 用户考试用了多久
            this.formExam.score_exam_time = this.duration;
            // (11) 考试结果
            let str = JSON.stringify(arr);
            str = str.replace(/"/g, '\\"');
            this.formExam.exam_options = str;
            // console.log("考试结果:", str);

            // 记录用户成绩
            let { user_name, score_val, score_exam_time, exam_options, exam_time, exam_type, topic_lib_id, exam_id, exam_name, exam_fullcredit, exam_passline } = this.formExam;
            await scoreAdd({ user_name, score_val, score_exam_time, exam_options, exam_time, exam_type, topic_lib_id, exam_id, exam_name, exam_fullcredit, exam_passline }).then(content => {
                console.log("last", content)
                if (content.code == 200) {
                    this.$message({
                        message: '提交试卷成功。',
                        type: 'success'
                    })
                    // 跳转我的成绩
                    this.$router.push({
                        path: '/mygrades'
                    })
                } else {
                    this.$message({
                        message: '提交试卷失败。',
                        type: 'warning'
                    })
                }
            })
                .catch(
                    err => {
                        console.log(err);
                    }
                )
        },


        // 阻止用户刷新页面
        // stopF5Refresh() {
        //     document.onkeydown = function (e) {
        //         var evt = window.event || e
        //         var code = evt.keyCode || evt.which
        //         // 屏蔽F1---F11
        //         if (code > 111 && code < 123) {
        //             if (evt.preventDefault) {
        //                 evt.preventDefault()
        //             } else {
        //                 evt.keyCode = 0
        //                 evt.returnValue = false
        //             }
        //         }
        //     }
        //     // 禁止鼠标右键菜单
        //     document.oncontextmenu = function (e) {
        //         return false
        //     }
        //     // 阻止后退的所有动作，包括 键盘、鼠标手势等产生的后退动作。
        //     history.pushState(null, null, window.location.href)
        //     window.addEventListener('popstate', function () {
        //         history.pushState(null, null, window.location.href)
        //     })
        // },
        // unload(e) {
        //     e = e || window.event
        //     if (e) {
        //         // 在这里阻止默认的刷新，弹出弹框
        //         e.returnValue = '关闭提示'
        //     }
        //     return '关闭'
        // }
    },

    created() {
        let topic_lib_id = this.$route.query.topic_lib_id;
        // this.topicDetailFunc(topic_lib_id);
        this.topicLibDetailFunc(topic_lib_id);
        this.scoreDetailFunc(topic_lib_id);
        // （8）记录考试ID
        this.formExam.exam_id = this.$route.query.exam_id
    },

    mounted() {
        // 浏览器刷新事件
        // window.addEventListener('beforeunload', this.unload)
        // this.stopF5Refresh()
        // 禁止鼠标右键菜单
        document.oncontextmenu = function () {
            return false
        }
    }
}

</script>

<style>
ul {
    padding: 0;
    margin: 0;
    list-style: none;
}

.examination .left,
.examination .right {
    min-height: 600px;
    background-color: #fff;
    margin-top: 20px;
    border-radius: 5px;
    padding: 10px;
}

.examination .title {
    height: 40px;
    background-color: #EEEEEE;
    text-align: center;
    line-height: 40px;
    font-size: 15px;
    margin: 0 0 10px 0;
}

.examination .box {
    margin: 0 0 10px 0;
}

.examination .box ul {
    width: 100%;
    display: grid;
    grid-template-rows: repeat(1, 36px);
    grid-template-columns: repeat(8, 36px);
    column-gap: 10px;
}

.examination .box ul li {
    background-color: #F4F4F5;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 36px;
    color: #666;
    border-radius: 5px;
    cursor: pointer;
}

.examination .box ul li.active {
    background-color: #FFF8E6;
    border: 1px solid #FFBA00;
    color: #FFBA00;
}

.single-choice .quest {
    padding: 5px 0;
    font-weight: bold;
}

.single-choice .opt li {
    margin-top: 10px;
    height: 36px;
    border: 1px solid #ccc;
    line-height: 40px;
    padding: 0 10px;
    border-radius: 2px;
    color: #666;
    cursor: pointer;
}

.single-choice .opt li.active {
    background-color: #409EFF;
    color: #fff;
}

.single-choice .opt li:hover {
    /* background-color: #f0f0f0; */
    /* color: #333; */
}

.examination .el-button--warning {
    background-color: #FFBA00;
    border: 1px solid #FFBA00;
}
</style>